package crm8000.services

import crm8000.Models.GoodsUnit;
import crm8000.helper.Result;
import grails.transaction.Transactional

@Transactional
class GoodsService {

	def IdGenService idGenService
	
    def allUnits() {
		return GoodsUnit.listOrderByName()
    }
	
	Result editUnit(GoodsUnit unit) {
		if (unit.unitId) {
			// 编辑
			def u = GoodsUnit.countByNameAndUnitIdNotEqual(unit.name, unit.unitId)
			if (u > 0) {
				unit.discard()
				return new Result(success: false, msg: "商品计量单位 [${unit.name}] 已经存在")
			}
		} else {
			// 新增
			def u = GoodsUnit.countByName(unit.name)
			if (u > 0) {
				unit.discard()
				return new Result(success: false, msg: "商品计量单位 [${unit.name}] 已经存在")
			}
			
			unit.unitId = idGenService.newId() 
		}
		
		unit.save()
		
		return new Result(success: true, id: unit.unitId)
	}
	
	Result deleteUnit(String unitId) {
		def unit = GoodsUnit.findByUnitId(unitId)
		unit?.delete()
		
		return new Result(success: true)
	}
}
